<?php

class Vs_FbLogin extends Module {

	const DEFAULT_GROUP = 2;
	const DISCOUNT_ID = 2;
	
	private static $cookie;
	private static $cart;
	private static $customer;
	
	function __construct() 
	{
	    $this->name = 'vs_fblogin';
	    $this->tab = 'front_office_features';
	    $this->version = '0.1.0';
	    $this->author = 'VS Solutions';
	    
	    parent::__construct();
	    $this->displayName = $this->l('Facebook Login');
	    $this->description = $this->l('Custommers login with theirs facebook accounts.');
	}
	                                                                            
	public function install()
	{
		return (parent::install() && $this->registerHook('header'));
	}
	                                                                            
	public function getContent()
	{
		
	    return $this->_html;
	}
	                                                                                                                                
	
	public function hookHeader($params)
	{	
		global $smarty;
		
		self::$cookie = $params['cookie'];
		self::$cart = $params['cart'];
		
		if($params['cookie']->isLogged()) { // Za versiqta na Alessa 
		//if(Context::getContext()->customer->isLogged()) {
			return false;
		}
		
		
		if(Tools::isSubmit("submitFbLogin")) {
//die(var_dump($_POST));
			$fbData['email']    = Tools::getValue('email');
			
			$fbData['gender']      = Tools::getValue('gender');
			$fbData['first_name']  = Tools::getValue('first_name');
			$fbData['last_name']   = Tools::getValue('last_name');
			$fbData['birthday']    = Tools::getValue('birthday');
			
			$fbData['name']     = Tools::getValue('name');
			$fbData['imageSrc'] = Tools::getValue('imageSrc');
	
			$customerId = Customer::customerExists($fbData['email'], true);
			if($customerId) {
				$customer = new Customer($customerId);
		
				if($customer->id_default_group != self::DEFAULT_GROUP) {
					$customer->id_default_group = self::DEFAULT_GROUP;
					$customer->save();
				}
			}
			else {
				$customer = $this->_createAccount($fbData);
			}
				
			if($customer) {
				$this->_createSession($customer);
				Tools::redirect(Tools::getValue('returnUrl'));
			}
		}
		
		
		Tools::addCSS($this->_path.'vs_fblogin.css', 'all');
		Tools::addJS($this->_path.'fb_init.js');
		
		
		$currentUrl = sprintf('%s%s', $_SERVER['PHP_SELF'], (!empty($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : ''));
		$smarty->assign('currentUrl', $currentUrl);
		
		return $this->display(__FILE__, 'vs_fblogin.tpl');
	}
	
	private function _createAccount($data)
	{
//die(var_dump($data));
		$customer = new Customer();
		
		$customer->email 	 = $data['email'];
		$customer->id_gender = $data['gender'] == 'male' ? 1 : 2;
		$customer->firstname  = $data['first_name'];
		$customer->lastname = $data['last_name'];
		$customer->passwd    = Tools::encrypt(Tools::passwdGen());
		
		if($data['birthday'] && $data['birthday'] != 'undefined') {
			$customer->birthday = date("Y-m-d", strtotime($data['birthday']));
		}
	
		$customer->id_default_group = self::DEFAULT_GROUP;
		$customer->add();
	
		/*
		 * If Add Customer Error
		*/
		if ($customer->id) {
			return $customer;
		}
		else {
			$this->logs[] = $this->l('Cannot create customer');
			return null;
		}
	
	}
	
	private function _createSession($customer)
	{
		global $smarty;
		
		self::$cookie->id_compare = isset(self::$cookie->id_compare) ? self::$cookie->id_compare: CompareProduct::getIdCompareByIdCustomer($customer->id);
		self::$cookie->id_customer = (int)($customer->id);
		self::$cookie->customer_lastname = $customer->lastname;
		self::$cookie->customer_firstname = $customer->firstname;
		self::$cookie->logged = 1;
		$customer->logged = 1;
		self::$cookie->is_guest = $customer->isGuest();
		self::$cookie->passwd = $customer->passwd;
		self::$cookie->email = $customer->email;
	
		// Add customer to the context
		self::$customer = $customer;
	
		if (Configuration::get('PS_CART_FOLLOWING') && (empty(self::$cookie->id_cart) || Cart::getNbProducts(self::$cookie->id_cart) == 0))
			self::$cookie->id_cart = (int)Cart::lastNoneOrderedCart(self::$customer->id);
	
		/* Update cart address */
		self::$cart->id_carrier = 0;
		self::$cart->id_address_delivery = Address::getFirstCustomerAddressId((int)($customer->id));
		self::$cart->id_address_invoice = Address::getFirstCustomerAddressId((int)($customer->id));
		// If a logged guest logs in as a customer, the cart secure key was already set and needs to be updated
		self::$cart->secure_key = $customer->secure_key;
		self::$cart->update();
		Module::hookExec('authentication');
	}
}

?>
